package guidePage;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.wxapi.MyWxApi;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import utils.KeyBoard;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.VariousUtils;

/**
 * Created by admin on 2017/2/15.
 * 登录界面
 */

@ContentView(R.layout.login_page)
public class LoginPage extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.login_back)
    private ImageView login_back;
    @ViewInject(R.id.login_register)
    private TextView login_register;
    @ViewInject(R.id.login_phone_edt)
    private EditText login_phone_edt;
    @ViewInject(R.id.login_pwd_edt)
    private EditText login_pwd_edt;
    @ViewInject(R.id.login_btn)
    private Button login_btn;
    @ViewInject(R.id.login_weichat_btn)
    private ImageView login_weichat_btn;//微信登录

    private final int REQUEST_CODE = 1;
    private String phoneNum = "";
    private String pwd = "";
    private MyReceiver myReceiver;

    private static final String TAG = "LoginPage";

    private Dialog dialog;

    private ErrorPageHandler myHandler = new ErrorPageHandler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    switch (msg.arg1) {
                        case 0:
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                if (jsonObject.getString("err_code").equals("0")) {
                                    SharedPreferences.Editor edit = SPUtils.getSharedPreferences().edit();
                                    edit.putString(Constant.USER_ID, jsonObject.getString("id"));
                                    edit.commit();
                                    MyLogUtils.e(TAG, SPUtils.getSharedPreferences().getString(Constant.USER_ID, ""));
                                    Intent intent = new Intent(Constant.ACTION_LOGIN);
                                    LoginPage.this.sendBroadcast(intent);
                                    LoginPage.this.setResult(REQUEST_CODE);
                                    LoginPage.this.finish();
                                    LoginPage.this.overridePendingTransition(0, R.anim.zoomout);//设置退出动画
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case 1:

                            break;
                        default:
                            break;
                    }

                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        showKeyBoard();
        registerBroadCast();//注册微信登录成功的广播接收
        login_phone_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                listenInputState();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        login_pwd_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                listenInputState();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private void initView() {
        login_back.setOnClickListener(this);
        login_register.setOnClickListener(this);
        login_weichat_btn.setOnClickListener(this);
        login_btn.setOnClickListener(this);
    }

    private void showKeyBoard() {
        KeyBoard.showKeyBoard();
    }

    private void listenInputState() {
        phoneNum = login_phone_edt.getText().toString();
        pwd = login_pwd_edt.getText().toString();
        if (!phoneNum.isEmpty()) {
            if (pwd.length() >= 6) {
                login_btn.setBackground(LoginPage.this.getResources().getDrawable(R.drawable.shape_login_focusable));
            } else {
                login_btn.setBackground(LoginPage.this.getResources().getDrawable(R.drawable.shape_login_unfocusable));
            }
        } else {
            login_btn.setBackground(LoginPage.this.getResources().getDrawable(R.drawable.shape_login_unfocusable));
        }
    }

    //按物理键退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();  //finish当前activity
            overridePendingTransition(0, R.anim.zoomout);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_back:
                LoginPage.this.finish();
                overridePendingTransition(0, R.anim.zoomout);//设置退出动画
                break;
            case R.id.login_register:
                Intent i = new Intent(LoginPage.this, RegisterPage.class);
                startActivityForResult(i, REQUEST_CODE);
                break;
            case R.id.login_btn://登录
                Login();
                break;
            case R.id.login_weichat_btn:
                //微信
                addLoadingView();
                boolean login = MyWxApi.Login();
                if (!login) {
                    if (null != dialog) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    private void registerBroadCast() {
        IntentFilter intentFilter = new IntentFilter(Constant.WEIXIN_ACITION_HASLOAD);
        myReceiver = new MyReceiver();
        this.registerReceiver(myReceiver, intentFilter);
    }

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            if (!TextUtils.isEmpty(code)) {
                //登录
                weiXinLogin(code);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == this.REQUEST_CODE) {
            if (resultCode != RESULT_CANCELED) {
                setResult(this.REQUEST_CODE);
                LoginPage.this.finish();
                overridePendingTransition(0, R.anim.zoomout);//设置退出动画
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            this.unregisterReceiver(myReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != dialog) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    private void Login() {
        //先清空userId的记录
        SharedPreferences.Editor edit = SPUtils.getSharedPreferences().edit();
        edit.putString(Constant.USER_ID, "");
        edit.commit();
        HashMap<String, String> hashMap = new HashMap<>();
        String clientid = SPUtils.getSharedPreferences().getString(Constant.CLIENTID, "");
        String phoneType = android.os.Build.MODEL; // 手机型号
        String androidType = Build.VERSION.RELEASE; // 当前安卓系统版本
        hashMap.put("ver", VariousUtils.getVersion());
        hashMap.put("os", "android");
        hashMap.put("deviceinfo", phoneType + ":" + androidType);
        hashMap.put("clientid", clientid);
        hashMap.put("tel", phoneNum);
        hashMap.put("pwd", pwd);
        new InterNetController(LoginPage.this, Constant.LOGIN, myHandler, hashMap, 0);
    }

    private void weiXinLogin(String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("from", "Android");
        hashMap.put("code", code);
        String clientid = SPUtils.getSharedPreferences().getString(Constant.CLIENTID, "");
        String phoneType = android.os.Build.MODEL; // 手机型号
        String androidType = Build.VERSION.RELEASE; // 当前安卓系统版本
        hashMap.put("ver", VariousUtils.getVersion());
        hashMap.put("os", "android");
        hashMap.put("deviceinfo", phoneType + ":" + androidType);
        hashMap.put("clientid", clientid);
        new InterNetController(this, Constant.WXLOGINSUCCESS, myHandler, hashMap, 0);
    }

    private void addLoadingView() {
        dialog = new Dialog(this, R.style.waitingDialog);
        dialog.setContentView(R.layout.waitting_layout);
        dialog.show();
        ImageView waiting_ima = (ImageView) dialog.findViewById(R.id.waiting_ima);
        Animation an = new RotateAnimation(0.0f, +350.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        an.setDuration(3000);
        an.setRepeatCount(Animation.INFINITE);
        an.setRepeatMode(Animation.RESTART);
        an.setInterpolator(new LinearInterpolator());
        waiting_ima.startAnimation(an);
    }
}

